# -*- encoding: UTF-8 -*-
# ---------------------------------import------------------------------------
import json
import os
import datetime


FILE_ENCODING = 'UTF-8'


class FileDataBase(object):
    """
    文档型简易json数据库
    """

    def __init__(self, db_path: str):
        self.__path = db_path

    def show_data_bases(self):
        """搜索文档目录，返回寻找到的数据集合"""
        # 搜寻文档目录
        db_list = list()
        for item_name in os.listdir(self.__path):
            # 判断是否是Sector并返回Sector
            if os.path.isdir(os.path.join(self.__path, item_name)) and os.path.exists(
                os.path.join(self.__path, item_name, BaseSector.__index_file_name__)
            ):
                db_list.append(os.path.join(self.__path, item_name))
            else:
                pass
        return db_list


class DayDataBase(object):
    """
    以日期为排布的数据文件夹，文件夹内文件必须以日期为名称，日期格式 YYYY-MM-DD
    """

    def __init__(self, db_path: str):
        if not os.path.isdir(db_path):
            raise FileNotFoundError('File Path Not Legal {}'.format(db_path))
        else:
            pass
        self.__path = db_path
        self.__data_dict = dict()
        self.hard_drive_init()

    def hard_drive_init(self):
        self.__data_dict = dict()
        self.hard_drive_extend()

    def hard_drive_extend(self):
        for date_str in os.listdir(self.__path):
            if date_str.endswith('json'):
                date_item = datetime.datetime.strptime(date_str.strip('.json'), '%Y-%m-%d').date()
                assert isinstance(date_item, datetime.date), 'Not Date Expression {}'.format(
                    os.path.join(self.__path, date_str)
                )
                with os.open(os.path.join(self.__path, date_str), os.O_RDONLY) as f:
                    self.__data_dict[date_item] = json.load(f)
                    f.close()
            else:
                pass

    def hard_drive_storage(self):
        for date_key, data_item in self.__data_dict.items():
            assert isinstance(date_key, datetime.date)
            with os.open(os.path.join(self.__path, date_key.strftime('%Y-%m-%d')), os.O_WRONLY) as f:
                json.dump(data_item, f)
                f.close()


# class BaseSector(object):
#     """数据集合，内含若干表格"""
#     __index_file_name__ = '__sector_index__.json'
#
#     def __init__(self, sector_path: str):
#         self.__path__ = sector_path
#         self.structure = json.load(open(os.path.join(self.__path__, )))
#
#     def __repr__(self):
#         return 'FileBaseSector {}, Located {}'.format(self.name, self.__path__)
#
#     @property
#     def name(self):
#         return self.__path__.split(os.path.sep)[-1]
